#coding:utf8
'''
Created on 2017/2/28
19:53
@author: Moon
qq : 550302989
'''

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from flask import Flask,request,render_template,session,redirect,url_for
from Services.UserService import UserManage
from Services.TaskService import TaskManage
from Services.TaskCommentService import TaskCommentManage

app = Flask(__name__)
app.secret_key='4ycXYFoe51d1T8tUX4gXCnOk'


@app.route('/')
def index():

    task_result = {}

    if len(session)>=1:
        if session['username']:
            # 获取用户id
            user_info = UserManage().findUserInfoForName(session['username'])
            if user_info['code'] == 0:
                userid=user_info['result'][0]
            # 根据用户id显示用户进行中的任务
            task_info = TaskManage().findUserProgressTask(userid)
            if task_info['code'] == 0:
                task_result = task_info['result']


    return render_template('index.html',task_result=task_result)

# 任务列表
# 历史任务
@app.route('/task/tasklist')
def tasklist():
    tasklist={}
    taskhistory={}
    tasklist_info = TaskManage().findUndoneTask()
    taskhistory_info = TaskManage().findHistoryTask()
    if tasklist_info['code'] == 0:
        tasklist = tasklist_info['result']
    if taskhistory_info['code'] == 0:
        taskhistory = taskhistory_info['result']

    return render_template("tasklist.html",tasklist=tasklist,taskhistory=taskhistory)

# 添加任务
@app.route('/task/addtask')
def addtask():
    return render_template("addtask.html")

# 任务列表2
@app.route('/task/tasklist2')
def datatable():
    result={}
    task_info = TaskManage().findUndoneTask()
    if task_info['code'] == 0:
        result = task_info['result']

    return render_template("tasklist2.html",result=result)

# 任务信息
@app.route('/task/taskinfo/<taskid>')
def taskinfo(taskid):
    tasklist = {}
    taskcomment_list = {}
    userlist = {}
    # 显示任务信息
    task_info = TaskManage().findTaskInfoForID(taskid)
    if task_info['code'] == 0:
        tasklist = task_info['result']
    # 显示评论信息
    taskcomment_info = TaskCommentManage().findComment(taskid)
    if taskcomment_info['code'] == 0:
        taskcomment_list = taskcomment_info['result']
    # 显示回复信息
        # 暂时不写
    # 判断 如果任务是已完成状态 显示评分信息
    #显示所有用户
    user_info = UserManage().findUsersInfo()
    if user_info['code'] == 0:
        userlist = user_info['result']
    print userlist


    return render_template('taskinfo.html',tasklist=tasklist,taskcomment_list=taskcomment_list,userlist=userlist)


# 登录
@app.route('/login',methods=['POST','GET'])
def login():
    success = {}
    error = {}
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if username!='' and password!='':
            userManage = UserManage()
            checkuser = userManage.checkUser(username,password)
            if checkuser['code'] == 0:
                session['username']=username
                return redirect(url_for('index'))
            else:
                print 1
                error = {
                    'code' : checkuser['code'],
                    'message' : "请填写正确的用户名和密码",
                }
        else:
            error={
                'code' : 1,
                'message' : "请填写正确的用户名和密码",
            }
    return render_template('login.html',success=success,error=error)

# 退出登录
@app.route('/loginout')
def loginout():
    del session['username']
    return redirect(url_for('login'))

# 注册
@app.route('/register',methods=['POST','GET'])
def register():
    success = {}
    error = {}
    if request.method == "POST":
        user_info = request.form.to_dict()
        print user_info
        if user_info['name'] != "" and user_info['password'] != "" and user_info['qq'] != "" and user_info['phone'] != "" and user_info['email'] != "":
            if user_info['password'] == user_info['password2']:
                user_info['authrank']=3
                userManage = UserManage()
                if userManage.checkUserName(user_info['name'])['code'] !=0 :
                    adduser = userManage.addUser(user_info)
                    if adduser['code'] == 0:
                        success = {
                            'code' : adduser['code'],
                            'message' : '注册'+adduser['message'],
                        }
                        return render_template('login.html',success=success)
                    else:
                        error = {
                            'code' : user_info['code'],
                            'message' : '注册'+user_info['message'],
                        }
                else:
                    error = {
                            'code' : user_info['code'],
                            'message' : '注册失败，用户已被注册'
                        }
            else:
                error = {
                        'code' : 1,
                        'message' : '注册失败，2次密码不一致'
                    }
        else:
            error = {
                        'code' : 1,
                        'message' : '注册失败，请正确填写信息'
                    }
    return render_template('register.html',error=error)




if __name__ == "__main__":
    app.run(host='0.0.0.0',port=8080,debug=True)